<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use app\validate\CheckPartner;
use think\exception\ValidateException;


// 合作伙伴
class Partner extends BaseController
{
    public function index()
    {
        return View::fetch();
    }


    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];

        if (!empty($get['key'])) {
            $where[] = ['name|email|department', 'like', '%'.$get['key'].'%'];
        }
        $total = Db::name('partner')
            ->where($where)
            ->count();

        $rows = Db::name('partner')
            ->where($where)
            ->order('sort', 'asc')
            ->page($get['page'], $get['limit'])
            ->select();

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function add()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        return View::fetch();
    }


    public function save(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckPartner::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {
            $data = array(
                'name'       => $post['name'],
                'head'       => $post['head'],
                'department' => $post['department'],
                'email'      => $post['email'],
                'add_time'   => time(),
            );
            if (!Db::name('partner')->insert($data)) {
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    /*
     * 修改
     */
    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }
        
        $id = $request->param('id');
        $inf = Db::name('partner')->find($id);
        View::assign('inf',$inf);
        return View::fetch();
    }


    public function modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckPartner::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {
            $update = array(
                'id'         => $post['id'],
                'name'       => $post['name'],
                'head'       => $post['head'],
                'department' => $post['department'],
                'email'      => $post['email'],
            );
            if (!Db::name('partner')->update($update)) {
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //+banner删除
    public function delete(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        try {

            if (!Db::name('partner')->where('id', 'in', $id)->delete()) {
                return $this->outputAjax('删除失败！');
            }
            return $this->outputAjax('删除成功！',0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    /*
 * 排序
 * date: 2019-04-10
 * author: admin
 */
    public function sort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }

        if (!is_numeric($post['sort'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['sort'] < 0 || $post['sort'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }

        Db::startTrans();
        try {

            $res = Db::name('partner')->where(array('id'=>$post['id']))->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }


            $rows = Db::name('partner')
                ->where('id', '<>', $post['id'])
                ->where('sort', '>=', $post['sort'])
                ->order('sort', 'asc')
                ->select();

            if (!Db::name('partner')->where('id', '=', $post['id'])->update(['sort' => $post['sort']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['sort']+1;
            foreach ($rows as &$v) {
                if ($v['sort'] != $i) {
                    if (!Db::name('partner')->where('id', '=', $v['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }
                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);

        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }
}